package com.rpay.admin.config.security;

import com.rpay.model.admin.RpayAdminUser;
import com.rpay.model.admin.RpayAdminUserRole;
import com.rpay.service.admin.impl.SecUserRoleServiceImpl;
import com.rpay.service.admin.impl.SystemUserServiceImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("MyUserDetailsImpl")
public class MyUserDetailsService implements UserDetailsService {

    @Resource(name = "systemUserServiceImpl")
    private SystemUserServiceImpl systemUserService;

    @Resource(name = "userRoleServiceImpl")
    private SecUserRoleServiceImpl userRoleService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        RpayAdminUser user;
        try {
            user = systemUserService.findByName(userName);
        } catch (Exception e) {
            throw new UsernameNotFoundException("user select fail");
        }
        if (user == null) {
            throw new UsernameNotFoundException("no user found");
        } else {
            try {
                List<RpayAdminUserRole> roles = userRoleService.getRoleByUser(user);
                return new MyUserDetails(user, roles);
            } catch (Exception e) {
                throw new UsernameNotFoundException("user role select fail");
            }
        }
    }
}